package com.bawei.es.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.es.service.EsIndexService;
import com.bawei.system.domain.vo.IndexInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Service
@Slf4j
public class EsIndexServiceImpl implements EsIndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final String INDEX_NAME="product_info";

    @Value("classpath:mappings/product_info.json")
    private Resource jsonResource;

    @Override
    public R<Boolean> indexCreate(String indexName) {
        //如果索引为空 抛出异常
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("索引名称不能为空");
        }
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        try {
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if (createIndexResponse.isAcknowledged()) {
                return R.ok(true);
            }
        } catch (IOException e) {
            log.error("连接ES服务异常:{}", e);
            throw new RuntimeException("创建索引失败，请联系管理员或查看服务日志");
        }
        return R.fail(false, "索引创建失败");
    }

    @Override
    public R<Boolean> indexExit(String indexName) {
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("indexName不能为空");
        }
        GetIndexRequest indexRequest = new GetIndexRequest(indexName);
        try {
            boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
            return R.ok(exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail(false, "查询失败！");
    }

    @Override
    public R<Boolean> indexDelete(String indexName) {
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("indexName不能为空 ");
        }
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        try {
            AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
            if (delete.isAcknowledged()) {
                return R.ok(true, "删除成功！");
            }
        } catch (IOException e) {
            log.error("删除索引失败：{}", e);
            throw new RuntimeException("调用es服务删除索引失败，详情请查看日志");
        }
        return R.fail(false, "删除索引失败");
    }

    @Override
    public R<Boolean> indexCreateWithMapping(String indexName, String indexMapping) {


        if (StringUtils.isEmpty(indexName) ||
                StringUtils.isEmpty(indexMapping)) {
            throw new ServiceException("indexName、indexMapping不能为空");
        }
        try {
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            Path path = Paths.get(jsonResource.getURI());
            byte[] bytes = Files.readAllBytes(path);
            String s = new String(bytes);
            Map map = JSONObject.parseObject(s, Map.class);
             request.mapping(map);
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if (createIndexResponse.isAcknowledged()) {
                return R.ok(true, "创建索引成功");
            }
        } catch (IOException e) {
            log.error("调用es创建索引异常：{}", e);
            throw new RuntimeException("创建索引失败");
        }

        return R.fail(false, "创建索引失败");
    }

    @Override
    public R<Map> indexGetMapping(String indexName) {
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("indexName不能为空");
        }
        GetMappingsRequest request = new GetMappingsRequest().indices(indexName);
        try {
            GetMappingsResponse response = restHighLevelClient.indices().getMapping(request, RequestOptions.DEFAULT);
            Map<String, MappingMetaData> mappings = response.mappings();
            MappingMetaData mappingMetaData = mappings.get(indexName);
            Map<String, Object> stringObjectMap = mappingMetaData.sourceAsMap();
            return R.ok(stringObjectMap, "操作成功");
        } catch (IOException e) {
            log.error("根据索引名称获取Mapping异常:{}", e);
            throw new RuntimeException("根据索引名称获取Mapping异常");
        }
    }

    @Override
    public void createEsStyle(IndexInfo indexInfo) {

        if (StringUtils.isEmpty(indexInfo.getIndexName())) {
            throw new ServiceException("indexName不能为空");
        }
        R<Boolean> booleanR = indexExit(indexInfo.getIndexName());
        Boolean data = booleanR.getData();
        if (!data) {
            CreateIndexRequest request = new CreateIndexRequest(indexInfo.getIndexName());

            if (ObjectUtils.isNotEmpty(indexInfo.getMappings())) {

                request.mapping(JSON.toJSONString(indexInfo.getMappings()), XContentType.JSON);
            }
            if (ObjectUtils.isNotEmpty(indexInfo.getSettings())) {

                request.settings(JSON.toJSONString(indexInfo.getSettings()), XContentType.JSON);
            }

            try {
              restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                log.error("调用es创建索引异常：{}", e);
                throw new RuntimeException("创建索引失败");
            }

        }

    }

}
